<template>
    <!--添加备件使用-->
    <Modal :mask-closable="false" v-model="deviceVisible" class="modal-content-layout" :title="$t('fault.AddSpareParts')"
        width="40%">
        <Form ref="deviceForm" :model="formTop" label-position="top" :rules="validateDevice">
            <Row :gutter="16">
                <Col :span="12">
                <!--备件料号-->
                <FormItem :label="$t('fault.SparePartsName')" prop="materialName">
                    <Select v-if="!isDisabled" v-model="formTop.materialName" filterable clearable :disabled="isDisabled"
                        :remote-method="handleRemote" :loading="searchLoading" @on-select="handleChangeWl">
                        <Option v-for="(item, index) in numberList" :value="item.materialName" :key="index"
                            :label="item.materialName" />
                    </Select>
                    <Input v-if="isDisabled" v-model="formTop.materialName" disabled />
                </FormItem>
                </Col>
                <Col :span="12">
                <!--备件品名-->
                <FormItem :label="$t('fault.SparePart')" prop="materialName">
                    <Input v-model="formTop.materialCode" disabled />
                </FormItem>
                </Col>
            </Row>
            <Row :gutter="16">
                <Col :span="12">
                <!-- 库存数量 -->
                <FormItem :label="$t('库存数量')" prop="inventoryQuantity">
                    <InputNumber style="width:100%" v-model="formTop.inventoryQuantity"  :disabled="isDisabled"/>
                </FormItem>
                </Col>
                <Col :span="12">
                <!--备件规格-->
                <FormItem :label="$t('fault.SparePartsSpecification')" prop="materialModel">
                    <Input v-model="formTop.materialModel" disabled />
                </FormItem>
                </Col>
            </Row>
            <Row :gutter="16">
                <Col :span="12">
                <!--所需数量-->
                <FormItem :label="$t('fault.RequiredQuantity')" prop="usedQuantity">
                    <Input v-model="formTop.usedQuantity"/>
                </FormItem>
                </Col>
                <Col :span="12">
                <!--处理方式及结果-->
                <FormItem :label="$t('fault.TreatmentMethodAndResult')">
                    <Input v-model="formTop.handlingMethod" :disabled="isDisabled" />
                </FormItem>
                </Col>
            </Row>
        </Form>
        <div slot="footer">
            <Button type="default" @click="handleCancel">{{ $t('common.Cancle') }}</Button>
            <Button type="primary" :loading="loadingVisible" @click="handleOk">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
    </Modal>
</template>

<script>
export default {
    name: "addDeviceModal",
    data() {
        const validateNum = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('所需数量必填'));
            }
            // 模拟异步验证效果
            if (!/^[1-9][0-9]*$/.test(value)) {
                callback(new Error('请输入整数'));
            } else {
                callback();
            }
        };
        return {
            workorderNo: '',
            deviceMId_: '',
            orgId: '',
            deviceVisible: false,
            loadingVisible: false,
            searchLoading: false,
            isDisabled: false,
            formTop: {
                materialCode: '',
                materialName: '',
                materialModel: '',
                usedQuantity: '',
                handlingMethod: '',
            },
            validateDevice: {
                materialCode: [
                    { required: true, message: '备件料号必选', trigger: 'change' }
                ],
                // backupNo: [
                //     { required: true, message: '备件编号必选', trigger: 'change' }
                // ],
                materialName: [
                    { required: true, message: '备件编号必选', trigger: 'change' }
                ],
                // materialModel: [
                //     { required: true, message: '备件编号必选', trigger: 'change' }
                // ],
                usedQuantity: [
                    { required: true, validator: validateNum, trigger: 'blur' }
                ],
            },
            numberList: [],
            backupNoList: [],
            faultPosition: []
        }
    },
    methods: {
        show(workorderNo, row, deviceMId, orgId) {
            this.deviceVisible = true
            this.workorderNo = workorderNo
            this.deviceMId_ = deviceMId
            this.orgId = orgId
            // 编辑
            if (row) {
                this.formTop = { ...row }
                this.isDisabled = true
            } else {
                this.$refs['deviceForm'].resetFields();
                delete this.formTop.id
                this.formTop.handlingMethod = ''
                this.isDisabled = false
                this.numberList = []
            }
        },
        handleRemote(query) {
            if (query !== "") {
                this.searchLoading = true;
                this.axios({
                    method: "post",
                    url: '/dms/material/page',
                    data: {
                        pageSize:99,
                        pageNum:1,
                        materialName: query,
                    },
                }).then((res) => {
                    if (res.code === 200) {
                        this.numberList = res.data.records
                    } else {
                        this.$Message.warning({
                            content: res.msg,
                            duration: 6,
                            closable: true,
                        });
                    }
                })
                .finally(() => {
                    this.searchLoading = false;
                });
            } else {
                this.numberList = [];
            }
        },
        handleChangeWl(val) {
            console.log(val)
            //materialName
            // let info = this.numberList.length ? this.numberList.filter(item => item.materialCode === val)[0] : {}
            const obj = this.numberList.find(item => item.materialName === val.value)

            if (obj) {
                this.formTop.materialName = obj.materialName;
                this.formTop.materialCode = obj.materialCode;
                this.formTop.materialModel = obj.materialModel
                this.formTop.inventoryQuantity = obj.inventoryQuantity || null
            }
            // this.backupNoList = info.purchaseNos || []
        },
        // handleChangeNo(val) {
        //     let info = this.backupNoList.length ? this.backupNoList.filter(item => item.purchaseOrderNo === val)[0] : {}
        //     this.formTop.materialName = info.materialName || ''
        //     this.formTop.materialModel = info.materialModel || ''
        //     this.formTop.materialPrice = info.purchasePrice || 0
        //     this.formTop.useOutInfoId = info.id
        // },
        handleCancel() {
            this.deviceVisible = false
            this.loadingVisible = false
        },
        handleOk() {
            this.$refs.deviceForm.validate((valid) => {
                if (valid) {
                    let params
                    if (this.formTop.id) {
                        params = {
                            usedQuantity: +this.formTop.usedQuantity,
                            handlingMethod: this.formTop.handlingMethod,
                            dmsMaintainId: this.workorderNo,
                            id: this.formTop.id,
                            materialCode: this.formTop.materialCode,
                            deviceMId: this.deviceMId_,
                            inventoryQuantity: this.formTop.inventoryQuantity || null
                        }
                    } else {
                        params = {
                            materialCode: this.formTop.materialCode,
                            // backupNo: this.formTop.backupNo,
                            materialName: this.formTop.materialName,
                            materialModel: this.formTop.materialModel,
                            usedQuantity: +this.formTop.usedQuantity,
                            handlingMethod: this.formTop.handlingMethod,
                            materialPrice: +this.formTop.materialPrice,
                            materialPriceCount: +this.formTop.usedQuantity * +this.formTop.materialPrice,
                            dmsMaintainId: this.workorderNo,
                            useOutInfoId: this.formTop.useOutInfoId,
                            deviceMId: this.deviceMId_,
                            inventoryQuantity: this.formTop.inventoryQuantity || null
                        }
                    }
                    this.axios({
                        method: "post",
                        url: this.formTop.id ? "/dms/deviceMaintenanceWorkOrder/updateMaintainBackupTemporary" : "/dms/deviceMaintenanceWorkOrder/addMaintainBackupTemporary",
                        data: params,
                    }).then((res) => {
                        if (res.code === 200) {
                            this.deviceVisible = false;
                            this.$Message.success(this.formTop.id ? "编辑成功" : "新建成功");
                            this.$emit("refresh");
                        } else {
                            this.$Message.error(res.msg);
                        }
                    });
                }
            })
        },
    }
}
</script>

<style scoped lang="scss">
/deep/.ivu-form-item-label {
    background: white !important;
    /*display: inline-block;*/
    /*width: 40%;*/
    /*height: 48px;*/
    /*line-height: 48px;*/
    /*background: #ffffff;*/
    /*text-align: right;*/
    border-right: 0 !important;
    /*padding-right: 10px;*/
}

/deep/.ivu-form-item {
    margin-bottom: 24px !important;
    border-right: 0 !important;
}
</style>
